#![forbid(unsafe_code)]

use std::sync::Arc;
use std::sync::Mutex;
use std::collections::HashMap;
use log::{info, warn, error};
use std::thread;
use std::time::Duration;

// 导入配置模块
pub mod config;
use config::SystemConfig;

// 导入safe_ffi库
use safe_ffi::core::error::{FFIError, FFIResult};
use safe_ffi::core::memory::SafeMemoryBuffer;
use safe_ffi::core::types::{CapabilityId, PhysicalAddress, VirtualAddress, ResourceType, MemoryPermissions};
use safe_ffi::exokernel::capability::{Capability, ThreadSafeCapability, create_thread_safe_capability};
use safe_ffi::exokernel::api;

// 能力包装器（安全地管理exokernel能力）
pub struct CapabilityWrapper {
    inner: Arc<ThreadSafeCapability>,
    acquired: bool,
}

impl CapabilityWrapper {
    // 创建新的能力包装器
    pub fn new(id: CapabilityId, resource_type: ResourceType) -> Self {
        CapabilityWrapper {
            inner: Arc::new(create_thread_safe_capability(id, resource_type)),
            acquired: false,
        }
    }

    // 获取能力
    pub fn acquire(&mut self) -> bool {
        if !self.acquired {
            let result = self.inner.acquire();
            if result {
                self.acquired = true;
                info!("Capability {} acquired", self.inner.id());
            } else {
                warn!("Failed to acquire capability {}", self.inner.id());
            }
            result
        } else {
            info!("Capability {} already acquired", self.inner.id());
            true
        }
    }

    // 释放能力
    pub fn release(&mut self) {
        if self.acquired {
            self.inner.release();
            self.acquired = false;
            info!("Capability {} released", self.inner.id());
        }
    }

    // 获取能力ID
    pub fn id(&self) -> CapabilityId {
        self.inner.id()
    }

    // 检查是否已获取
    pub fn is_acquired(&self) -> bool {
        self.acquired
    }
    
    // 获取内部ThreadSafeCapability引用
    pub fn get_inner(&self) -> Arc<ThreadSafeCapability> {
        Arc::clone(&self.inner)
    }
}

impl Drop for CapabilityWrapper {
    fn drop(&mut self) {
        self.release();
    }
}

// 服务管理器（管理所有系统服务）
pub struct ServiceManager {
    mem_service: Arc<Mutex<MemoryService>>,
    proc_service: Arc<Mutex<ProcessService>>,
    fs_service: Arc<Mutex<FileSystemService>>,
    net_service: Arc<Mutex<NetworkService>>,
    graphics_service: Arc<Mutex<GraphicsService>>,
    vulkan_service: Arc<Mutex<VulkanService>>,
    skia_service: Arc<Mutex<SkiaService>>,
    wayland_service: Arc<Mutex<WaylandService>>,
    ipc_service: Arc<Mutex<IPCService>>,
    driver_service: Arc<Mutex<DriverService>>,
    kuikly_service: Arc<Mutex<KuiklyUIService>>,
    graphics_subsystem: Arc<Mutex<GraphicsSubsystem>>,
    shell_service: Arc<Mutex<ShellService>>, // 添加Shell服务
    zed_service: Arc<Mutex<ZedService>>, // 添加Zed编辑器服务
    rustfs_service: Arc<Mutex<RustFSService>>, // 添加RustFS服务
    unigetui_service: Arc<Mutex<UniGetUIServiceImpl>>, // 添加UniGetUI服务
    capabilities: HashMap<String, CapabilityWrapper>,
}

impl ServiceManager {
    // 初始化服务管理器（使用默认配置）
    pub fn new() -> Result<Self, String> {
        let default_config = SystemConfig::default();
        Self::new_with_config(&default_config)
    }
    
    // 使用自定义配置初始化服务管理器
    pub fn new_with_config(config: &SystemConfig) -> Result<Self, String> {
        // 获取初始能力
        let (mem_cap, cpu_cap) = match Self::get_initial_capabilities() {
            Err(err) => return Err(err),
        };

        // 创建内存服务
        let mem_service = Arc::new(Mutex::new(
            MemoryService::new(mem_cap.get_inner()).map_err(|e| format!("Failed to initialize memory service: {}", e))?
        ));

        // 创建进程服务
        let proc_service = Arc::new(Mutex::new(
            ProcessService::new(cpu_cap.get_inner(), Arc::clone(&mem_service))
                .map_err(|e| format!("Failed to initialize process service: {}", e))?
        ));

        // 创建文件系统服务
        let fs_service = Arc::new(Mutex::new(
            FileSystemService::new().map_err(|e| format!("Failed to initialize file system service: {}", e))?
        ));

        // 创建网络服务
        let net_service = Arc::new(Mutex::new(
            NetworkService::new().map_err(|e| format!("Failed to initialize network service: {}", e))?
        ));

        // 创建图形服务
        let graphics_service = Arc::new(Mutex::new(
            GraphicsService::new(mem_cap.get_inner()).map_err(|e| format!("Failed to initialize graphics service: {}", e))?
        ));

        // 创建Vulkan服务
        let vulkan_service = Arc::new(Mutex::new(
            VulkanService::new(Arc::clone(&graphics_service), mem_cap.get_inner())
                .map_err(|e| format!("Failed to initialize Vulkan service: {}", e))?
        ));

        // 创建Skia服务
        let skia_service = Arc::new(Mutex::new(
            SkiaService::new(
                Arc::clone(&graphics_service),
                Arc::clone(&vulkan_service),
                mem_cap.get_inner()
            ).map_err(|e| format!("Failed to initialize Skia service: {}", e))?
        ));

        // 创建Wayland服务
        let wayland_service = Arc::new(Mutex::new(
            WaylandService::new(Arc::clone(&graphics_service), mem_cap.get_inner())
                .map_err(|e| format!("Failed to initialize Wayland service: {}", e))?
        ));

        // 创建IPC服务
        let ipc_service = Arc::new(Mutex::new(
            IPCService::new(mem_cap.get_inner())
                .map_err(|e| format!("Failed to initialize IPC service: {}", e))?
        ));

        // 创建驱动服务
        let driver_service = Arc::new(Mutex::new(
            DriverService::new(mem_cap.get_inner())
                .map_err(|e| format!("Failed to initialize driver service: {}", e))?
        ));

        // 创建Kuikly UI服务
        let kuikly_service = Arc::new(Mutex::new(
            KuiklyUIService::new(mem_cap.get_inner())
                .map_err(|e| format!("Failed to initialize Kuikly UI service: {}", e))?
        ));

        // 创建图形子系统服务 - 整合Wayland、Skia、Vulkan和Kuikly
        let graphics_subsystem = Arc::new(Mutex::new(
            GraphicsSubsystem::new(
                Arc::clone(&graphics_service),
                Arc::clone(&vulkan_service),
                Arc::clone(&skia_service),
                Arc::clone(&wayland_service),
                Arc::clone(&kuikly_service),
                mem_cap.get_inner()
            ).map_err(|e| format!("Failed to initialize graphics subsystem: {}", e))?
        ));
        
        // 创建Shell服务 - 提供zsh集成功能
        let shell_service = Arc::new(Mutex::new(
            ShellService::new(mem_cap.get_inner(), Arc::clone(&proc_service))
                .map_err(|e| format!("Failed to initialize Shell service: {}", e))?
        ));

        // 创建Zed编辑器服务
        let zed_service = Arc::new(Mutex::new(
            ZedService::new(ZedConfig::default()).map_err(|e| format!("Failed to initialize Zed service: {}", e))?
        ));

        // 创建RustFS服务
        let rustfs_service = Arc::new(Mutex::new(
            RustFSService::new(RustFSConfig::default()).map_err(|e| format!("Failed to initialize RustFS service: {}", e))?
        ));

        // 创建UniGetUI服务
        let unigetui_service = Arc::new(Mutex::new(
            UniGetUIServiceImpl::new()
        ));

        // 存储能力
        let mut capabilities = HashMap::new();
        capabilities.insert("memory".to_string(), mem_cap);
        capabilities.insert("cpu".to_string(), cpu_cap);

        // 尝试获取Zed能力
        if let Some(cap) = capabilities.get_mut("zed") {
            if !cap.acquire() {
                warn!("Failed to acquire Zed capability");
            }
        }

        Ok(ServiceManager {
            mem_service,
            proc_service,
            fs_service,
            net_service,
            graphics_service,
            vulkan_service,
            skia_service,
            wayland_service,
            ipc_service,
            driver_service,
            kuikly_service,
            graphics_subsystem,
            shell_service,
            zed_service,
            rustfs_service,
            unigetui_service,
            capabilities,
        })
    }

    // 获取初始能力
    fn get_initial_capabilities() -> Result<(CapabilityWrapper, CapabilityWrapper), String> {
        match api::get_initial_capabilities() {
            Ok((mem_cap_id, cpu_cap_id)) => {
                let mut mem_cap = CapabilityWrapper::new(mem_cap_id, ResourceType::Memory);
                let mut cpu_cap = CapabilityWrapper::new(cpu_cap_id, ResourceType::Cpu);

                // 尝试获取能力
                if !mem_cap.acquire() || !cpu_cap.acquire() {
                    return Err("Failed to acquire initial capabilities".to_string());
                }

                info!("Successfully acquired initial capabilities: memory={}, cpu={}", 
                      mem_cap_id, cpu_cap_id);

                Ok((mem_cap, cpu_cap))
            },
            Err(err) => Err(format!("Failed to get initial capabilities: {:?}", err))
        }
    }

    // 获取内存服务
    pub fn get_memory_service(&self) -> Arc<Mutex<MemoryService>> {
        Arc::clone(&self.mem_service)
    }

    // 获取进程服务
    pub fn get_process_service(&self) -> Arc<Mutex<ProcessService>> {
        Arc::clone(&self.proc_service)
    }

    // 获取文件系统服务
    pub fn get_filesystem_service(&self) -> Arc<Mutex<FileSystemService>> {
        Arc::clone(&self.fs_service)
    }

    // 获取网络服务
    pub fn get_network_service(&self) -> Arc<Mutex<NetworkService>> {
        Arc::clone(&self.net_service)
    }

    // 获取图形服务
    pub fn get_graphics_service(&self) -> Arc<Mutex<GraphicsService>> {
        Arc::clone(&self.graphics_service)
    }

    // 获取Vulkan服务
    pub fn get_vulkan_service(&self) -> Arc<Mutex<VulkanService>> {
        Arc::clone(&self.vulkan_service)
    }

    // 获取Skia服务
    pub fn get_skia_service(&self) -> Arc<Mutex<SkiaService>> {
        Arc::clone(&self.skia_service)
    }

    // 获取Wayland服务
    pub fn get_wayland_service(&self) -> Arc<Mutex<WaylandService>> {
        Arc::clone(&self.wayland_service)
    }

    // 获取IPC服务
    pub fn get_ipc_service(&self) -> Arc<Mutex<IPCService>> {
        Arc::clone(&self.ipc_service)
    }
    
    // 获取驱动服务
    pub fn get_driver_service(&self) -> Arc<Mutex<DriverService>> {
        Arc::clone(&self.driver_service)
    }
    
    // 获取Kuikly UI服务
    pub fn get_kuikly_service(&self) -> Arc<Mutex<KuiklyUIService>> {
        Arc::clone(&self.kuikly_service)
    }
    
    // 获取图形子系统服务
    pub fn get_graphics_subsystem(&self) -> Arc<Mutex<GraphicsSubsystem>> {
        Arc::clone(&self.graphics_subsystem)
    }
    
    // 获取Shell服务
    pub fn get_shell_service(&self) -> Arc<Mutex<ShellService>> {
        Arc::clone(&self.shell_service)
    }

    // 获取Zed编辑器服务
    pub fn get_zed_service(&self) -> Arc<Mutex<ZedService>> {
        Arc::clone(&self.zed_service)
    }

    // 获取RustFS服务
    pub fn get_rustfs_service(&self) -> Arc<Mutex<RustFSService>> {
        Arc::clone(&self.rustfs_service)
    }
    
    // 获取UniGetUI服务
    pub fn get_unigetui_service(&self) -> Arc<Mutex<UniGetUIServiceImpl>> {
        Arc::clone(&self.unigetui_service)
    }
    
    // 启动所有服务
    pub fn start_all_services(&self) -> Result<(), String> {
        // 启动内存服务
        self.mem_service.lock().map_err(|e| format!("Failed to lock memory service: {}", e))?
            .start()?;

        // 启动进程服务
        self.proc_service.lock().map_err(|e| format!("Failed to lock process service: {}", e))?
            .start()?;

        // 启动文件系统服务
        self.fs_service.lock().map_err(|e| format!("Failed to lock file system service: {}", e))?
            .start()?;

        // 启动网络服务
        self.net_service.lock().map_err(|e| format!("Failed to lock network service: {}", e))?
            .start()?;

        // 启动图形服务
        self.graphics_service.lock().map_err(|e| format!("Failed to lock graphics service: {}", e))?
            .start()?;

        // 启动Vulkan服务
        self.vulkan_service.lock().map_err(|e| format!("Failed to lock Vulkan service: {}", e))?
            .start()?;

        // 启动Skia服务
        self.skia_service.lock().map_err(|e| format!("Failed to lock Skia service: {}", e))?
            .start()?;

        // 启动Wayland服务
        self.wayland_service.lock().map_err(|e| format!("Failed to lock Wayland service: {}", e))?
            .start()?;

        // 启动IPC服务
        self.ipc_service.lock().map_err(|e| format!("Failed to lock IPC service: {}", e))?
            .start()?;
            
        // 启动驱动服务
        self.driver_service.lock().map_err(|e| format!("Failed to lock driver service: {}", e))?
            .start()?;
            
        // 启动Kuikly UI服务
        self.kuikly_service.lock().map_err(|e| format!("Failed to lock Kuikly UI service: {}", e))?
            .start()?;
        
        // 启动图形子系统服务 - 整合Wayland、Skia、Vulkan和Kuikly
        self.graphics_subsystem.lock().map_err(|e| format!("Failed to lock Graphics Subsystem: {}", e))?
            .initialize()
            .map_err(|e| format!("Failed to initialize Graphics Subsystem: {:?}", e))?;
        
        self.graphics_subsystem.lock().map_err(|e| format!("Failed to lock Graphics Subsystem: {}", e))?
            .start()
            .map_err(|e| format!("Failed to start Graphics Subsystem: {:?}", e))?;
            
        // 启动Shell服务
        self.shell_service.lock().map_err(|e| format!("Failed to lock Shell service: {}", e))?
            .start()
            .map_err(|e| format!("Failed to start Shell service: {}", e))?;

        // 启动Zed服务
        self.zed_service.lock().map_err(|e| format!("Failed to lock Zed service: {}", e))?
            .start()
            .map_err(|e| format!("Failed to start Zed service: {}", e))?;

        // 启动RustFS服务
        self.rustfs_service.lock().map_err(|e| format!("Failed to lock RustFS service: {}", e))?
            .start()
            .map_err(|e| format!("Failed to start RustFS service: {}", e))?

        // 启动UniGetUI服务
        self.unigetui_service.lock().map_err(|e| format!("Failed to lock UniGetUI service: {}", e))?
            .initialize()
            .map_err(|e| format!("Failed to initialize UniGetUI service: {}", e))?

        info!("All services started successfully");
        Ok(())
    }
}

// 内存管理服务（在exokernel上构建）
pub mod mem_service;
use mem_service::MemoryService;

// 进程管理服务
pub mod proc_service;
use proc_service::ProcessService;

// 文件系统服务
pub mod fs_service;
use fs_service::FileSystemService;

// 网络服务
pub mod net_service;
use net_service::NetworkService;

// 图形服务
pub mod gfx_service;
use gfx_service::GraphicsService;

// Vulkan服务
pub mod vulkan_service;
use vulkan_service::VulkanService;

// Skia服务
pub mod skia_service;
use skia_service::SkiaService;

// Wayland服务
pub mod wayland_service;
use wayland_service::WaylandService;

// IPC服务
pub mod ipc_service;
use ipc_service::IPCService;

// 驱动服务
pub mod driver_service;
use driver_service::DriverService;

// 网络抽象层
pub mod network_abstraction;

// 各平台网络驱动适配器
pub mod linux_network_driver;
pub mod reactos_network_driver;
pub mod haikuos_network_driver;
pub mod openharmony_network_driver;

// Kuikly UI服务
pub mod kuikly_service;
use kuikly_service::KuiklyUIService;

// 桌面环境服务
pub mod desktop_environment;
use desktop_environment::DesktopEnvironment;

// 图形子系统服务 - 整合Wayland、Skia、Vulkan和Kuikly
pub mod graphics_subsystem;
use graphics_subsystem::GraphicsSubsystem;

// Shell服务 - 提供zsh集成功能
pub mod shell_service;
use shell_service::ShellService;

// Zed编辑器服务 - 集成Zed编辑器功能
pub mod zed_service;
use zed_service::ZedService;
use zed_service::ZedConfig;

// RustFS服务 - 集成RustFS分布式对象存储
pub mod rustfs_service;
use rustfs_service::{RustFSService, RustFSConfig};

// UniGetUI服务 - 集成UniGetUI包管理功能
pub mod unigetui_service;
use unigetui_service::{UniGetUIService, UniGetUIServiceImpl};